package UDP.Demo2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSender {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket
            DatagramSocket socket = new DatagramSocket();

            // 广播地址（255.255.255.255）或子网广播地址（如192.168.1.255）
            InetAddress broadcastAddress = InetAddress.getByName("255.255.255.255");
            int port = 9876;

            String message = "这是一条UDP广播消息！";
            byte[] sendData = message.getBytes();

            // 发送广播数据包
            DatagramPacket sendPacket = new DatagramPacket(
                    sendData, sendData.length, broadcastAddress, port);
            socket.send(sendPacket);
            System.out.println("广播消息已发送: " + message);

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
